from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, List
from schemas import UserOut
from dependencies import get_current_user
import pandas as pd
import numpy as np

def get_market_router(app):
    """Create and configure market router with access to FastAPI app"""
    router = APIRouter(prefix="/api/market", tags=["Market"])

    @router.get("/summary", response_model=Dict[str, List[dict]])
    async def get_market_summary(current_user: UserOut = Depends(get_current_user)):
        """Get market summary with sums of POWERLINE, volume, sharpe_ratio, and amount by date, ordered by date descending"""
        try:
            df = app.state.df
            if df is None:
                raise HTTPException(status_code=500, detail="后端数据未加载")

            # Ensure required columns exist
            required_columns = ['date', 'POWERLINE', 'volume', 'sharpe_ratio', 'amount']
            missing_columns = [col for col in required_columns if col not in df.columns]
            if missing_columns:
                raise HTTPException(status_code=500, detail=f"Parquet 文件中缺少列: {missing_columns}")

            # Group by date and calculate sums
            summary_df = df.groupby('date').agg({
                'POWERLINE': lambda x: x.fillna(0).sum(),  # Replace NaN with 0 for POWERLINE
                'volume': 'sum',
                'sharpe_ratio': 'sum',
                'amount': 'sum'
            }).reset_index()

            # Sort by date in descending order
            summary_df = summary_df.sort_values('date', ascending=False)

            # Format the date and replace NaN with None for JSON compatibility
            summary_df['date'] = summary_df['date'].astype(str)
            summary_df.replace({np.nan: None}, inplace=True)

            # Convert to list of dictionaries for response
            result = summary_df.to_dict('records')

            return {"summary": result}

        except HTTPException as http_exc:
            raise http_exc
        except Exception as e:
            print(f"获取市场总结数据时发生错误: {e}")
            raise HTTPException(status_code=500, detail=str(e))

    return router